package com.zyfu.mybatis.demo.mybatis;

import cn.hutool.core.bean.BeanDesc;
import cn.hutool.core.bean.BeanUtil;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * <b>拦截器, 对新增和批量新增进行了拦截</b>
 * 当新增数据时,为实体信息设置 createTime 和 updateTime
 *
 * @author 张永福
 * @since 2024/2/6 13:59
 */
@Component
@Intercepts(
        {
                /**
                 * 拦截 Executor 的 update方法, args与 update方法的入参一致
                 * org.apache.ibatis.executor.Executor#update(org.apache.ibatis.mapping.MappedStatement, java.lang.Object)
                 */
                @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}),
        }
)
public class InsertTimerInterceptor implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object[] args = invocation.getArgs();
        MappedStatement statements = (MappedStatement) args[0];
        if (!SqlCommandType.INSERT.equals(statements.getSqlCommandType())) {
            return invocation.proceed();
        }
        Object obj = args[1];
        String id = statements.getId();
        if (DaoMethodUtil.isBatchInsert(id)) {
            return invocation.proceed();
        }
        Date date = new Date();
        BeanDesc beanDesc = BeanUtil.getBeanDesc(obj.getClass());
        if (beanDesc.getProp("updateTime") != null) {
            BeanUtil.setFieldValue(obj, "updateTime", date);
        }
        if (beanDesc.getProp("createTime") != null) {
            BeanUtil.setFieldValue(obj, "createTime", date);
        }
        return invocation.proceed();
    }

}
